import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
// eslint-disable-next-line import/no-unresolved
import an8 from '@mmstudio/an000008';
import { tbpteam } from '../../../atoms/db';

const logger = anylogger('pages/api/team/add.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = Omit<ITbpteam, 'id'>;

/**
 * pages/api/team/add.api
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const body = req.body as Message;

		if (!body
			|| !body.briefintroduction
			|| !body.teamname
			|| !body.name
			|| !body.idphoto
			|| !body.originalclass
			|| !body.originalmajor
		) {
			res.status(200).json({
				ok: false,
				message: '缺少必要的参数'
			});
			return;
		}

		const id = an8();
		await tbpteam().insert({
			...body,
			team_id: id
		});
		res.status(200).json({ ok: true });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
